package com.zch.array_;

//lang包默认导入

import java.util.Arrays;
import java.util.Comparator;

@SuppressWarnings({"all"})
public class ArrayMethod {
    public static void main(String[] args) {

        Integer[] arr1 = {3, -1, 2, 4, 1};

        //自然排序
        Arrays.sort(arr1);
        System.out.println(Arrays.toString(arr1));

        //定制排序
        Arrays.sort(arr1, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2 - i1;
            }
        });
        System.out.println(Arrays.toString(arr1));

        //模拟排序
        int[] arr2 = {3, -1, 0, 5, 8};
        bubbleSort(arr2, new Comparator<Object>() {     //使用匿名内部类实现接口
            @Override
            public int compare(Object o1, Object o2) {
                int a = (Integer) o1;    //向下转型+拆箱
                int b = (Integer) o2;
                return b - a;
            }
        });
        System.out.println(Arrays.toString(arr2));
    }

    public static void bubbleSort(int[] arr, Comparator c) {    //Comparator是一个接口
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (c.compare(arr[j], arr[j + 1]) > 0) {     //即前一个>后一个时，进行交换
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}
